﻿/*
 * @author: wizardc
 */

using System;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Dou.UI
{
    /// <summary>
    /// 解决滚动区域中嵌套滚动区域导致的所有事件都被最里面的滚动区域接收的问题
    /// 比如一个垂直滚动区域中的item里有水平滚动的列表时
    /// 注意：该组件不要加在 ScrollRect 同一级的组件上，请添加到最下层的 ScrollRect 的 Viewport 组件上，并给 Viewport 添加可以进行交互的组件，比如 Image
    /// </summary>
    public class ScrollViewEventBroadcast : MonoBehaviour, IInitializePotentialDragHandler, IBeginDragHandler, IDragHandler, IEndDragHandler, IScrollHandler
    {
        /// <summary>
        /// 接收水平滚动事件的水平滚动区域
        /// </summary>
        public GameObject scrollHorizontal;

        /// <summary>
        /// 接收垂直滚动事件的水平滚动区域
        /// </summary>
        public GameObject scrollVertical;

        private Vector2 _pos;
        private GameObject scrollObj;

        public void OnInitializePotentialDrag(PointerEventData eventData)
        {
            _pos = eventData.position;
            ExecuteEvents.Execute(scrollHorizontal, eventData, ExecuteEvents.initializePotentialDrag);
            ExecuteEvents.Execute(scrollVertical, eventData, ExecuteEvents.initializePotentialDrag);
        }

        public void OnBeginDrag(PointerEventData eventData)
        {
            _pos = eventData.position - _pos;
            float x = Math.Abs(_pos.x);
            float y = Math.Abs(_pos.y);
            scrollObj = x > y ? scrollHorizontal : scrollVertical;
            ExecuteEvents.Execute(scrollObj, eventData, ExecuteEvents.beginDragHandler);
        }

        public void OnDrag(PointerEventData eventData)
        {
            ExecuteEvents.Execute(scrollObj, eventData, ExecuteEvents.dragHandler);
        }

        public void OnEndDrag(PointerEventData eventData)
        {
            ExecuteEvents.Execute(scrollObj, eventData, ExecuteEvents.endDragHandler);
        }

        public void OnScroll(PointerEventData eventData)
        {
            ExecuteEvents.Execute(scrollObj, eventData, ExecuteEvents.scrollHandler);
        }
    }
}
